package com.mwumz.third.common;

import java.util.ArrayList;
import java.util.function.Function;

/**
 * @Author: wumz
 * @Date: 2020/7/2 15:12
 * @Version 1.0
 */
public class PageList<E> extends ArrayList<E> {
    private long pageNum;
    private long pageSize;
    private long startRow;
    private long endRow;
    private long totalCount;
    private long totalPage;

    public PageList() {
    }

    public PageList(long pageNum, long pageSize, long totalCount) {
        super(0);
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.totalCount = totalCount;
        this.calculateStartAndEndRow();
    }

    private void calculateStartAndEndRow() {
        this.startRow = this.pageNum > 0L ? (this.pageNum - 1L) * this.pageSize : 0L;
        this.endRow = this.startRow + this.pageSize * (long)(this.pageNum > 0L ? 1 : 0);
    }

    public long getPageNum() {
        return this.pageNum;
    }

    public void setPageNum(long pageNum) {
        this.pageNum = pageNum;
    }

    public long getPageSize() {
        return this.pageSize;
    }

    public PageList<E> setPageSize(long pageSize) {
        this.pageSize = pageSize;
        this.calculateStartAndEndRow();
        return this;
    }

    public long getStartRow() {
        return this.startRow;
    }

    public long getEndRow() {
        return this.endRow;
    }

    public long getTotalCount() {
        return this.totalCount;
    }

    public PageList<E> setTotalCount(long totalCount) {
        this.totalCount = totalCount;
        if (this.pageSize > 0L) {
            this.totalPage = totalCount / this.pageSize + (long)(totalCount % this.pageSize == 0L ? 0 : 1);
        } else {
            this.totalPage = 0L;
        }

        return this;
    }

    public long getTotalPage() {
        return this.totalPage;
    }

    public PageList<E> setTotalPage(long totalPage) {
        this.totalPage = totalPage;
        return this;
    }

    public <R> PageList<R> map(Function<? super E, ? extends R> mapper) {
        PageList<R> mappedPageList = new PageList(this.pageNum, this.pageSize, this.totalCount);
        this.forEach((e) -> {
            R apply = mapper.apply(e);
            mappedPageList.add(apply);
        });
        return mappedPageList;
    }
}
